package com.cpit.platform.security.handler;

import com.cpit.platform.common.constant.LogConstant;
import com.cpit.platform.common.entity.Result;
import com.cpit.platform.common.utils.LogUtils;
import com.cpit.platform.dto.OperLog;
import com.cpit.platform.service.OperLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LogoutSuccessLogHandler extends SimpleUrlLogoutSuccessHandler {

    @Autowired
    private OperLogService operLogService;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Authentication authentication) throws IOException, ServletException {

        UserDetails user = (UserDetails) authentication.getPrincipal();

        OperLog operLog = LogUtils.createOperLog(LogConstant.MODULE_SECURITY, LogConstant.OPER_LOGOUT,
                Result.CODE_SUCCESS, user.getUsername(), user.getUsername());
        operLogService.writeLog(operLog);

        super.onLogoutSuccess(httpServletRequest, httpServletResponse, authentication);
//        httpServletResponse.sendRedirect("/");
    }
}
